﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using PIM.API;

public partial class Recipe : System.Web.UI.Page
{
    PIMServices pimService = new PIMServices();
    private int _RecipeId = 0;
    private string UserIdOfRecipe = "";
    protected void Page_Load(object sender, EventArgs e)
    {
        //if (Request.QueryString["RecipeId"] != null)
        //{
        //    _RecipeId = Convert.ToInt32(Request.QueryString["RecipeId"].ToString());
        //}
        //if (!IsPostBack)
        //{
        //    GetRecipeUser(_RecipeId);
        //}
        try
        {
            if (Request.QueryString["RecipeId"] != null)
            {
                _RecipeId = Convert.ToInt32(Request.QueryString["RecipeId"].ToString());
                if (Session["Userid"] != null)
                {
                    if (!IsPostBack)
                    {

                        GetRecipeUser(_RecipeId);
                        btnEdit.Visible = true;
                        btnUpload.Visible = false;
                        if (Session["Userid"].ToString() == UserIdOfRecipe)
                        {
                            btnDelete.Visible = true;
                        }
                    }
                }
                else
                {
                    if (!IsPostBack)
                    {

                        GetRecipeUser(_RecipeId);
                    }
                }
            }
            else
            {
                ScriptManager.RegisterStartupScript(Page, typeof(Page), "Call InitRating", "initRating()", true);
                btnSave.Visible = true;
                btnEdit.Visible = false;
                btnUpload.Visible = true;
                panel1.Visible = true;
                panel2.Visible = false;
            }
        }
        catch (Exception ex)
        {

        }
        

    }

    public void GetRecipeUser(int RecipeId)
    {
        try
        {
            RecipeUser Recipe = pimService.GetRecipeUserByRecipe(RecipeId);
            if (Recipe != null)
            {
                txtDescription.Text = Recipe.Description;
                txtRecDirection.Text = Recipe.RecDirection;
                txtRecipeName.Text = Recipe.RecipeName;
                txtIngredient.Text = Recipe.IngredientName;
                hdImage.Value = Recipe.RecipeImage;
                UserIdOfRecipe = Recipe.UserID.ToString();
                txtServing.Text = Recipe.Serving.ToString();
                chIsPublish.Checked = Recipe.IsShared;
                Checkbox1.Checked = Recipe.IsShared;
                ratingStar.Value = Recipe.RecipeRating.ToString();
                //$(".basic1").attr('data-average', fillrating);
                //ScriptManager.RegisterClientScriptBlock(Page, typeof(Page), "error", "$('.basic1').attr('data-average','5');", true);
                ScriptManager.RegisterStartupScript(Page, typeof(Page), "Call InitRating", "initRating()", true);
                if(!string.IsNullOrEmpty(Recipe.RecipeImage))
                    Image2.Src = "data:image/jpeg;charset=utf-8;base64," + Recipe.RecipeImage;
                //Fill Panel 2
                lblDescription.Text = Recipe.Description;
                lblRecDirection.Text = Recipe.RecDirection.Replace(Environment.NewLine, "<br>");
                lblRecipeName.Text = Recipe.RecipeName;
                lblIngredient.Text = Recipe.IngredientName.Replace(Environment.NewLine, "<br>");
                lblServing.Text = Recipe.Serving.ToString();
            }
        }
        catch (Exception ex)
        {
        }
    }

    protected void btnInsertRecipe_Click(object sender, EventArgs e)
    {
        ScriptManager.RegisterStartupScript(Page, typeof(Page), "Call InitRating", "initRating()", true);
        try
        {
            string userId = "";

            if (Session["Userid"] != null)
                userId = Session["Userid"].ToString();


            if (_RecipeId == 0)
            {
                string[] _Ingredient = new string[0];
                string _strIngredient = txtIngredient.Text.Replace("\r\n", "|");
                if (!string.IsNullOrEmpty(txtIngredient.Text))
                    _Ingredient = _strIngredient.Split('|');
                string a = txtIngredient.Text;
                double rating = 5;
                if (!string.IsNullOrEmpty(ratingStar.Value))
                    rating = Convert.ToDouble(ratingStar.Value);
                int result = pimService.InsertRecipe(Convert.ToInt32(userId), Convert.ToInt32(userId), 1, txtRecipeName.Text, Convert.ToInt32(txtServing.Text), 6, 7, hdImage.Value, txtDescription.Text,
                                                rating, txtRecDirection.Text, txtIngredient.Text, chIsPublish.Checked);
                if (result > -1)
                {
                    if (_Ingredient.Count() > 0)
                    {
                        pimService.DeleteAllRecipeIngredient(result);
                        foreach (string str in _Ingredient)
                        {
                            string _rs = pimService.InsertRecipeIngredientUser(result, str, 0, 0, 0);
                        }
                    }
                    // ScriptManager.RegisterStartupScript(this, this.Page.GetType(), "Success", "alert('Insert Recipe Successful')", true);
                    Response.Redirect("MyRecipe.aspx");
                }
                else
                {
                    ScriptManager.RegisterStartupScript(this, this.Page.GetType(), "Error", "alert('Can not Create Recipe')", true);
                }
            }
            else
            {
                RecipeUser Recipe = pimService.GetRecipeUserByRecipe(_RecipeId);
                if (!string.IsNullOrEmpty(userId))
                {
                    int _idUser = Convert.ToInt32(userId);
                    int _createUserId = Convert.ToInt32(userId);

                    string[] _Ingredient = new string[0];
                    int result = -1;
                    if (_idUser == Recipe.UserID)
                    {
                        //Update Recipe Old User

                        string _strIngredient = txtIngredient.Text.Replace("\r\n", "|");
                        if (!string.IsNullOrEmpty(txtIngredient.Text))
                            _Ingredient = _strIngredient.Split('|');

                        string RecipeUpdate = pimService.UpdateRecipe(_RecipeId, txtRecipeName.Text, Recipe.UserID, Convert.ToInt32(txtServing.Text), 40,
                                                30, hdImage.Value, txtDescription.Text, Recipe.RecipeRating, txtRecDirection.Text, txtIngredient.Text, chIsPublish.Checked);
                        Image2.Src = "data:image/jpeg;charset=utf-8;base64," + hdImage.Value;
                        if (RecipeUpdate.Equals("True"))
                        {
                            if (_Ingredient.Count() > 0)
                            {
                                pimService.DeleteAllRecipeIngredient(_RecipeId);
                                foreach (string str in _Ingredient)
                                {
                                    string _rs = pimService.InsertRecipeIngredientUser(_RecipeId, str, 0, 0, 0);
                                }
                            }
                            //ScriptManager.RegisterStartupScript(this, this.Page.GetType(), "Success", "alert('Updated Recipe Successful')", true);
                            Response.Redirect("MyRecipe.aspx");
                        }
                        else
                        {
                            ScriptManager.RegisterStartupScript(this, this.Page.GetType(), "Error", "alert('Can not Update a')", true);
                        }

                    }
                    else
                    {
                        /*
                         1. Kiem tra _UserId nay da co recipe do chua (bang cach check RecipeName va UserId)
                         * (if(exists(select * from RecipeUser where UserId=_UserId and RecipeName=Recipe.RecipeName)))
                         * {
                         *  update
                         * }
                         * else insert
                         */
                        RecipeUser recipeUser = pimService.GetRecipeUserByNameAndUserId(Recipe.RecipeName, _idUser);
                        if (recipeUser != null)
                        {
                            //Update Recipe
                            string _strIngredient = txtIngredient.Text.Replace("\r\n", "|");
                            if (!string.IsNullOrEmpty(txtIngredient.Text))
                                _Ingredient = _strIngredient.Split('|');

                            string RecipeUpdate = pimService.UpdateRecipe(recipeUser.RecipeID, txtRecipeName.Text, recipeUser.UserID, Convert.ToInt32(txtServing.Text), 40,
                                                    30, hdImage.Value, txtDescription.Text, recipeUser.RecipeRating, txtRecDirection.Text, txtIngredient.Text, chIsPublish.Checked);
                            Image2.Src = "data:image/jpeg;charset=utf-8;base64," + hdImage.Value;
                            if (RecipeUpdate.Equals("True"))
                            {
                                if (_Ingredient.Count() > 0)
                                {
                                    pimService.DeleteAllRecipeIngredient(recipeUser.RecipeID);
                                    foreach (string str in _Ingredient)
                                    {
                                        string _rs = pimService.InsertRecipeIngredientUser(recipeUser.RecipeID, str, 0, 0, 0);
                                    }
                                }
                                //ScriptManager.RegisterStartupScript(this, this.Page.GetType(), "Success", "alert('Updated Recipe Successful')", true);
                                Response.Redirect("MyRecipe.aspx");
                            }
                            else
                            {
                                ScriptManager.RegisterStartupScript(this, this.Page.GetType(), "Error", "alert('Can not Update')", true);
                            }


                        }
                        else
                        {
                            //Insert Recipe
                            // string userId = Session["UserId"].ToString();
                            string _strIngredient = txtIngredient.Text.Replace("\r\n", "|");
                            if (!string.IsNullOrEmpty(txtIngredient.Text))
                                _Ingredient = _strIngredient.Split('|');
                            string a = txtIngredient.Text;
                            result = pimService.InsertRecipe(_idUser, _createUserId, 1, txtRecipeName.Text, Convert.ToInt32(txtServing.Text), 6, 7, hdImage.Value, txtDescription.Text, 5
                                                            , txtRecDirection.Text, txtIngredient.Text, chIsPublish.Checked);
                            if (result > -1)
                            {
                                if (_Ingredient.Count() > 0)
                                {
                                    pimService.DeleteAllRecipeIngredient(result);
                                    foreach (string str in _Ingredient)
                                    {
                                        string _rs = pimService.InsertRecipeIngredientUser(result, str, 0, 0, 0);
                                    }
                                }
                                // ScriptManager.RegisterStartupScript(this, this.Page.GetType(), "Success", "alert('Insert Recipe Successful')", true);
                                Response.Redirect("MyRecipe.aspx");
                            }
                            else
                            {
                                ScriptManager.RegisterStartupScript(this, this.Page.GetType(), "Error", "alert('Can not Create Recipe')", true);
                            }

                        }

                    }

                }
            }
        }
        catch (Exception ex)
        {

        }

    }


    protected void btn_Click(object sender, EventArgs e)
    {
        ScriptManager.RegisterStartupScript(Page, typeof(Page), "Call InitRating", "initRating()", true);
        try
        {
            if (panel2.Visible)
            {
                btnEdit.Text = "Cancel";
                btnUpload.Visible = true;
                //GetRecipeUser(_RecipeId);
                btnSave.Visible = true;
                panel1.Visible = true;
                panel2.Visible = false;

            }
            else
            {
                btnEdit.Text = "Edit";
                btnUpload.Visible = false;
                btnSave.Visible = false;
                panel1.Visible = false;
                panel2.Visible = true;
            }
        }
        catch (Exception ex)
        {

        }
    }

    protected void btnDelete_Click(object sender, EventArgs e)
    {
        ScriptManager.RegisterStartupScript(Page, typeof(Page), "Call InitRating", "initRating()", true);
        bool check = Convert.ToBoolean(pimService.CheckRecipeOfMealPlan(_RecipeId));
        if (check)
        {
            ScriptManager.RegisterStartupScript(this, this.GetType(), "Message", "confirm('This recipe exits in the my mealplan. Are you delete?');", true);

        }
        else
        {
            bool result = Convert.ToBoolean(pimService.DeleteRecipe(_RecipeId));
            if (result)
            {
                Response.Redirect("../MyRecipe.aspx");
            }
            else
            {
                ScriptManager.RegisterStartupScript(this, this.Page.GetType(), "Error", "alert('Can not Delete Recipe')", true);
            }
        }
    }
}